package com.fengxu.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
*@Description 群聊客户端
*@Author 风珝
*@Date 2020/12/3 14:10
*@Version 1.0.0
*/
public class ChatClient {

    private final String serverHost = "127.0.0.1";
    private final int port = 6666;
    private SocketChannel socketChannel = null;
    private Selector selector = null;
    private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<>(10);

    public ChatClient(){
        try {
            socketChannel = SocketChannel.open();
            selector = Selector.open();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            socketChannel.connect(new InetSocketAddress(serverHost,port));
            while (!socketChannel.finishConnect());
            System.out.println("连接服务器成功.");
        } catch (IOException e) {
            System.out.println("连接服务器失败!!!");
        }
    }

    public void run(){
        try {
            while (true){
                if(selector.select(1000) == 0){
                    while(messageQueue.size() > 0){
                        String msg = messageQueue.remove();
                        try {
                            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
                            System.out.println("成功发送消息:"+msg);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    continue;
                }
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if(selectionKey.isReadable()){
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        channel.read(byteBuffer);
                        System.out.println("接受到服务器消息:"+new String(byteBuffer.array()));
                    }
                    iterator.remove();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String msg){
        messageQueue.add(msg);
    }
}
